package drp.snowbell.util.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

public class ReflectionHelper {

	private static TClassLoader loader = new TClassLoader();

	public static Class<? extends Object> getClass(Object obj) {
		return obj.getClass();
	}

	@SuppressWarnings("unchecked")
	public static <T> Class<T> getClass(String clazzName) {
		Class<T> ret = null;
		try {
			ret = (Class<T>) loader.loadClass(clazzName);
			// ret = (Class<T>) Class.forName(clazzName);
		} catch (ClassNotFoundException e) {
			// TODO 记录错误
			e.printStackTrace();
		}
		return ret;
	}

	public static <T> T newInstance(String clazzName, Object... initargs) {
		T obj = null;
		Class<T> clazz = getClass(clazzName);
		obj = newInstance(clazz, initargs);
		return obj;
	}

	@SuppressWarnings("unchecked")
	public static <T> T newInstance(Class<T> clazz, Object... initargs) {
		T obj = null;
		if (clazz != null) {
			Class<?>[] clazzs = new Class<?>[initargs.length];
			for (int i = 0; i < initargs.length; i++) {
				clazzs[i] = initargs[i].getClass();
			}
			Constructor<?> constructor;
			try {
				constructor = clazz.getConstructor(clazzs);
				obj = (T) constructor.newInstance(initargs);
			} catch (Exception e) {
				// TODO 记录错误
				e.printStackTrace();
			}
		}
		return obj;
	}

	public static void addPath(String dirOrJar) {
		loader.addPath(dirOrJar);
	}

	/**
	 * 根据名称获取方法.但是必须保证这个名称只有一个方法.如果多个的话返回第一个.
	 * 
	 * @param name
	 * @return
	 */
	public static Method getMethodByName(Class<?> clazz, String name) {
		Method ret = null;
		if (clazz != null) {
			Method[] list = clazz.getMethods();
			for (Method method : list) {
				if (method.getName().equals(name)) {
					ret = method;
					break;
				}
			}
		}
		return ret;
	}

	public static Class<?> defineClass(String name, byte[] b) {
		return loader.defineClass(name, b);
	}
}
